package org.helyx.gae.getabike.provider.details;

import java.io.InputStream;
import java.util.Date;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.helyx.gae.getabike.content.accessor.ContentAccessor;
import org.helyx.gae.getabike.content.provider.exception.ContentProviderException;
import org.helyx.gae.getabike.model.City;
import org.helyx.gae.getabike.model.StationDetails;
import org.helyx.gae.getabike.xml.ElementAttributeAccessor;
import org.helyx.gae.getabike.xml.ElementValueAccessor;


public class VelibStationDetailsContentProvider extends AbstractStationDetailsContentProvider {

	private static final String ELT_STATION = "/station";
	
	private static final String ELT_AVAILABLE = "available";
	private static final String ELT_FREE = "free";
	private static final String ELT_TOTAL = "total";
	private static final String ELT_TICKET = "ticket";
	
	public VelibStationDetailsContentProvider() {
		super();
	}
	
	public StationDetails getStationDetails(InputStream inputStream, String stationId) throws ContentProviderException {
		try {
				
			StationDetails stationDetails = new StationDetails();
							
	        SAXReader reader = new SAXReader();
	        Document document = reader.read(inputStream);
			
			@SuppressWarnings("unchecked")
			Element stationElt = (Element)document.selectSingleNode(ELT_STATION);

			stationDetails.setDate(new Date());
			stationDetails.setStationNumber(stationId);

			ElementValueAccessor eltValueAccessor = new ElementValueAccessor();

			eltValueAccessor.selectElement(stationElt);
			
			stationDetails.setAvailable(eltValueAccessor.getEltValueAsInt(ELT_AVAILABLE));
			stationDetails.setFree(eltValueAccessor.getEltValueAsInt(ELT_FREE));

			stationDetails.setTotal(eltValueAccessor.getEltValueAsInt(ELT_TOTAL));
			stationDetails.setTicket(eltValueAccessor.getEltValueAsInt(ELT_TICKET) == 1);

			stationDetails.setHs(stationDetails.getTotal() - stationDetails.getFree() - stationDetails.getAvailable());

			return stationDetails;
		}
		catch (DocumentException e) {
			throw new ContentProviderException(e);
		}
		
	}

}
